package studio.raptor.dispatcher.server.handler.dispatch;

import java.io.IOException;
import java.util.List;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import studio.raptor.dispatcher.common.constant.EventStatus;
import studio.raptor.dispatcher.server.context.HandlerContext;
import studio.raptor.dispatcher.server.handler.Handler;
import studio.raptor.dispatcher.server.service.GraphService;

/**
 * 从图中获取可以处理的任务节点
 *
 * @author jack
 * @since 1.0
 */
@Component
public class FetchEventHandler extends Handler {

  private static final Logger log = LoggerFactory.getLogger(FetchEventHandler.class);

  @Autowired
  GraphService graphService;


  @Override
  public boolean process(HandlerContext context) {
    boolean result = false;
    try {
      Set<String> events = graphService.fetchEvent(context.getCode(), EventStatus.WAITED, 100);
      if (events!= null && !events.isEmpty()) {
        context.setEventIds(events);
        result = getSuccessor().process(context);
      }
    } catch (Exception e) {
      log.error("the consumer->{},fetch event id from graph server failed", context.getCode(), e);
    }
    return result;
  }
}
